package com.hk.wms.wmscustom83.controller;

import com.alibaba.nacos.api.exception.NacosException;
import com.hk.wms.wmscustom83.config.GetWmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class CustomController {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    GetWmsConfig getWmsConfig;
    @Value("${service-url.nacos-user-service}")
    String serverUrl;
    @Value("${service-url.wms-sso-url}")
    String ssoUrl;
    @Value("${config-url.config-service}")
    String configUrl;
    @Value("${service-url.wms-custom}")
    String self;
    @GetMapping("/custom/{id}")
    public  String getServerPort(@PathVariable("id") Integer id){
        return restTemplate.getForObject(serverUrl+"/provider/"+id,String.class);
    }
    @GetMapping("/config1")
    public  String getConfig1(){
        return restTemplate.getForObject(configUrl+"/config",String.class);
    }

    @GetMapping("/config")
    public String getConfig() {
        String info=null;
        try {
           info=getWmsConfig.get();
        } catch (NacosException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            return info;
        }
    }
    @GetMapping("/index")
    public String index(@CookieValue(value="sso_user",required=false)String ssoUserCookie,
                        @RequestParam(value="sso_user",required=false)String ssoUserParam,
                        HttpServletResponse response,
                        HttpServletRequest request){
        if(!StringUtils.isEmpty(ssoUserParam)){
            Cookie sso_user=new Cookie("sso_user",ssoUserParam);
            response.addCookie(sso_user);
            return "index";
        }
        if(StringUtils.isEmpty(ssoUserCookie)){
            System.out.println("进来了");
            //没有登录，跳转登录认证中心
            try {
                String s=ssoUrl+"?redirec_url="+self;
                System.out.println(s);
                response.sendRedirect(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }else{
            return "index";
        }

    }
}
